<?php
define(__UPLOAD__,'./Upload/');

function formatPrice($number)
{
	return sprintf("%.2f", $number);
}

function getIP()
{
	global $ip;
	if (getenv("HTTP_CLIENT_IP"))
		$ip = getenv("HTTP_CLIENT_IP");
	else if(getenv("HTTP_X_FORWARDED_FOR"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	else if(getenv("REMOTE_ADDR"))
		$ip = getenv("REMOTE_ADDR");
	else $ip = "0.0.0.0";
	return $ip;
}

function getIdenty()
{
	$User = new \Model\User();
	return $User->getIdenty();
}

function getIdentyName($userID = 0)
{
    if(empty($userID) == true)
    {
        $userID = getIdenty();
    }
    
    $userName = MOA('permission_user')->where(array('id'=>$userID))->getField('userName');
    return $userName;
}

function getIdentyRole($userID = 0)
{
    if(empty($userID) == true)
    {
        $userID = getIdenty();
    }

    $roleID = MOA('permission_user')->where(array('id'=>$userID))->getField('role');

    return $roleID;
}

function getGroupID($userID = 0)
{
    if(empty($userID) == true)
    {
        $userID = getIdenty();
    }
    
    $groupID = MOA('permission_user')->where(array('id'=>$userID))->getField('groupID');
    
    //$groupID = M('auth_group_access')->where(array('uid'=>getIdenty()))->getField('group_id');

	return $groupID;
}

function getGroupName($groupID = 0)
{
    if(empty($groupID) == true)
    {
        $groupID = getGroupID();
    }

    $groupName = MOA('permission_group')->where(array('id'=>$groupID))->getField('title');

    return $groupName;
}

function getGroupList($groupID = 0)
{
    if(empty($groupID) == false)
    {
        $groupList = MOA('permission_user')->where(array('groupID'=>$groupID,'status'=>1))->select();
    }
    else 
    {
        $groupList = MOA('permission_group')->where(array('parentID'=>array('neq',0),'status'=>1))->select();
    }

    return $groupList;
}

function menu(){

	$menu = MOA('menu')->where(array('pid' => 0,'status'=>1))->order('sort')->select();
	foreach ($menu as $key => $value)
	{
		$menu[$key]['parent'] = MOA('menu')->where(array('pid' => $value['id'],'status'=>1))->order('sort')->select();
		foreach ($menu[$key]['parent'] as $k => $v)
		{
			$menu[$key]['parent'][$k]['chlid'] = MOA('menu')->where(array('pid' => $v['id'],'status'=>1))->order('sort')->select();
		}
	}

	return $menu;
}

function subtext($text, $length)
{
	if(mb_strlen($text, 'utf8') > $length)	{
		return mb_substr($text, 0, $length, 'utf8').'...';	}
	return $text;
}

function exportExcel($excelObject,$file='data')
{
	vendor('PHPExcel.PHPExcel.Writer.Excel5');
	$objWriter = new \PHPExcel_Writer_Excel5($excelObject);
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
	header("Content-Type:application/force-download");
	header("Content-Type:application/vnd.ms-execl");
	header("Content-Type:application/octet-stream");
	header("Content-Type:application/download");
	header("Content-Disposition:attachment;filename=".$file.".xls");
	header("Content-Transfer-Encoding:binary");
	$objWriter->save("php://output");
}

function writeExcel()
{
	vendor('PHPExcel.PHPExcel');
	$PHPExcel = new \PHPExcel();
	$PHPExcel->getProperties()->setCreator("Tripvip");
	$PHPExcel->getProperties()->setLastModifiedBy("Tripvip");
	$PHPExcel->getProperties()->setTitle("Tripvip Report");
	$PHPExcel->getProperties()->setSubject("Tripvip Report");
	$PHPExcel->getProperties()->setDescription("Tripvip Report");
	return $PHPExcel;
}
function readExcel($filename)
{
	set_time_limit(180);
	@ini_set('memory_limit','128M');
	
	Vendor("PHPExcel.PHPExcel.IOFactory");
	$info = pathinfo($filename);
	if($info['extension'] == 'xls')
	{
		$objReader = \PHPExcel_IOFactory::createReader('Excel5');
	}
	else if($info['extension'] == 'xlsx')
	{
		$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
	}
	else if($info['extension'] == 'csv')
	{
		setlocale(LC_ALL, 'zh_CN');
		$objReader = \PHPExcel_IOFactory::createReader('CSV');
		$objReader->setInputEncoding('GBK');
		$objReader->setDelimiter(',');
	}
	else
	{
		return false;
	}

	$objReader->setReadDataOnly(true);
	$objReader = $objReader->load($filename);
	$sheet     = $objReader->getSheet(0);
	$Row       = $sheet->getHighestRow();
	$Column    = $sheet->getHighestColumn();
	$Column = PHPExcel_Cell::columnIndexFromString($Column);

	$array = array();

	for($currentRow = 1;$currentRow <= $Row;$currentRow++)
	{
		for($currentColumn= 0;$currentColumn<= $Column; $currentColumn++)
		{
			$value = $sheet->getCellByColumnAndRow($currentColumn,$currentRow)->getValue();
			$array[$currentRow][] = $value;
		}
	}
	
	return $array;
	exit;
}

function curlRequest($url,$method="GET",$data = '')
{
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_HEADER, 0);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	if($method=="POST")
	{
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
	}
	$return = curl_exec($curl);
	curl_close($curl);
	return $return;
}

function Upload()
{
	$upload = new \Think\Upload();
	$upload->autoSub = true;
	$upload->subName = array('date', 'Ymd');
	$upload->rootPath = __UPLOAD__;
	$upload->replace = true; //是否存在同名文件是否覆盖

	$valid = false;
	$msg = '';
	if($return = $upload->upload())
	{
		$valid = true;
		$msg = $return;
	}
	else
	{
		$msg = $upload->getError();
	}
	return array('valid'=>$valid,'msg'=>$msg);
}
function MOA($name)
{
	return M($name,'',C('DB_OA'));
}

function M3($name)
{
	return M($name,'cms_',C('DB_Tripvip'));
}

function sendSMS($mobile,$content)
{
	$url = 'http://211.147.252.14:8080/?';
	$params = array();
	$params['CORPID'] = 'lv001-0060';
	$params['USERNAME'] = 'tripvipcn';
	$params['PASSWORD'] = '111111';
	$params['EXTNO'] = '';
	$params['MOBILE'] = $mobile;
	$params['CONTENT'] =  urlencode(iconv("utf-8","gb2312//IGNORE",$content.'【Tripvip】'));
	 
	foreach ($params as $key => $value)
	{
		$url.= $key."=".$value."&";
	}
	$url = trim($url,'&');
	$return = curlRequest($url);
	return $return;
}

function getSMSVaildNumber()
{
	$url                = 'http://211.147.252.14:8080/Balance.asp?';
	$params             = array();
	$params['CORPID']   = 'lv001-0060';
	$params['USERNAME'] = 'tripvipcn';
	$params['PASSWORD'] = '111111';

	foreach ($params as $key => $value)
	{
		$url.= $key."=".$value."&";
	}

	$url    = trim($url,'&');
	$return = curlRequest($url);
	
	return $return;
}

function sendEmail($email,$subject,$content,$file = '')
{
	Vendor("PHPMailer.PHPmailer");
	
	$return = array('valid'=>true,'msg'=>'');
	
    $smtpServer	= 'smtp.exmail.qq.com';
    $smtpRport 	= 25;//SMTP服务器端口
    $smtpMail   = 'services@tripvip.cn';//SMTP服务器的用户邮箱
    $smtpUser   = 'services@tripvip.cn';//SMTP服务器的用户帐号
    $smtpPass   = 'keguanbuyao!@#$1234';//SMTP服务器的用户密码
    $smtpName	= '免签精选游';

    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host			= $smtpServer; //smtp服务器的名称（这里以126邮箱为例）
    $mail->SMTPAuth 	= true; //启用smtp认证
    $mail->Username 	= $smtpUser; //你的邮箱名
    $mail->Password 	= $smtpPass; //邮箱密码
    $mail->From 		= $smtpMail; //发件人地址（也就是你的邮箱地址）
    $mail->FromName 	= $smtpName; //发件人姓名
    //$mail->WordWrap 	= 50; //设置每行字符长度
    $mail->IsHTML(true); // 是否HTML格式邮件
    $mail->CharSet		= 'utf-8'; //设置邮件编码
    $mail->Subject 		= $subject; //邮件主题
    $mail->Body 		= $content; //邮件内容
    $mail->AltBody = "This is the body in plain text for non-HTML mail clients"; //邮件正文不支持HTML的备用显示
    	
    if(is_array($email) == true)
    {
    	foreach ($email as $key => $value)
    	{
    		$mail->AddAddress($value);
    	}
    }
    else
    {
    	$mail->AddAddress($email);
    }
    	
    if(empty($file)==false)
    {
    	$mail->AddAttachment(".".$file);
    }

    $status = $mail->Send();
    if($status == true)
    {
	    $return['msg'] = '发送成功';
    }
    else
    {
    	$return['valid'] = false;
    	$return['msg'] = $mail->ErrorInfo;;
    }

    return $return;
}

function getMessageList()
{
	$return = '';
	$userID = getIdenty();
	$userGroupID = getGroupID();
	if($userID != false)
	{
		$where = "receiveGroupID = {$userGroupID}";
		$visaMessageCount = MOA('message_visa')->where($where)->count();
		if($visaMessageCount > 0)
		{
			$return .= '<span><i><img src="/Public/image/mail2.png"></i> <a href="'.U('Message/visaReceive').'">签证流转['.$visaMessageCount.']</a></span>';
		}

		$refundPrice = MOA('order_refund')->group('orderID')->getField('orderID,sum(price)');
		$filterIDArr = array();
		foreach ($refundPrice as $key => $value)
		{
			$realPrice = MOA('order')->where(array('id'=>$key))->getField('realPrice');
			if($realPrice == $value)
			{
				$filterIDArr[] = $key;
			}
		}
		
//         //成本流转
// 		$costMessage = R('Message/orderCostCount',array(array('costStatus'=>'NF','makeOrderTimeStart'=>'2015-12-01')));
// 		if($costMessage['count'] != 0)
// 		{
// 		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$costMessage['url'].'">未确成本['.$costMessage['count'].']</a></span>';
// 		}
		
		//新成本流转
		$costMessage = R('orderCost/count',array(array('dealStatus'=>1)));
		if($costMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$costMessage['url'].'">成本流转['.$costMessage['count'].']</a></span>';
		}

		//退款流转
		$refundMessage = R('orderRefund/count',array(array('dealStatus'=>1)));
		if($refundMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$refundMessage['url'].'">退款流转['.$refundMessage['count'].']</a></span>';
		}
		
		//订单流转
		$processMessage = R('orderProcess/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
            $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$processMessage['url'].'">订单流转['.$processMessage['count'].']</a></span>';
		}
		
		//优惠流转
		$processMessage = R('orderDiscount/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$processMessage['url'].'">优惠流转['.$processMessage['count'].']</a></span>';
		}

		//切位款流转
		$processMessage = R('orderLoss/count',array(array('dealStatus'=>1,'typeStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$processMessage['url'].'">申请切位款['.$processMessage['count'].']</a></span>';
		}
		
		//预付款流转
		$processMessage = R('orderLoss/count',array(array('dealStatus'=>1,'typeStatus'=>2)));
		if($processMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$processMessage['url'].'">申请预付款['.$processMessage['count'].']</a></span>';
		}
		
		//付款流转
		$processMessage = R('orderPayment/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$processMessage['url'].'">申请付款['.$processMessage['count'].']</a></span>';
		}

		//未处理单据
		$formMessage = R('Form/count');
		if($formMessage != 0)
		{
			$return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.U("Form/applyList",array('checkType'=>1,'status'=>1)).'">未处理单据['.$formMessage.']</a></span>';
		}
		
		//收款流转
		$processMessage = R('orderReceivables/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$processMessage['url'].'">收款流转['.$processMessage['count'].']</a></span>';
		}
		
		//供应商审核
		$supplierMessage = R('supplierCheck/count',array(array('dealStatus'=>1)));
		
		if($supplierMessage['count'] != 0)
		{
		    $return .= '&nbsp;&nbsp;<span><i><img src="/Public/image/mail2.jpg"></i> <a href="'.$supplierMessage['url'].'">供应商审核['.$supplierMessage['count'].']</a></span>';
		}
	}
	return $return;
}

function getMessageNum()
{
	$return = 0;
	$userID = getIdenty();
	$userGroupID = getGroupID();
	if($userID != false)
	{
// 		$where = "(sendID = {$userID} and sendTag = 1) or (receiveID = {$userID} and receiveTag = 1) or (receiveGroupID = {$userGroupID} and receiveID = 0) ";
// 		$orderMessageCount = M('message_order')->where($where)->count();
// 		$return += $orderMessageCount;
		$where = "receiveGroupID = {$userGroupID}";
		$visaMessageCount = MOA('message_visa')->where($where)->count();
		$return += $visaMessageCount;
		
// 		//成本流转
// 		$costMessage = R('Message/orderCostCount',array(array('costStatus'=>'NF','makeOrderTimeStart'=>'2015-12-01')));
// 		if($costMessage['count'] != 0)
// 		{
// 		    $return += $costMessage['count'];
// 		}
		
		//新成本流转
		$costMessage = R('orderCost/count',array(array('dealStatus'=>1)));
		if($costMessage['count'] != 0)
		{
		    $return += $costMessage['count'];
		}
		
		//退款流转
		$refundMessage = R('orderRefund/count',array(array('dealStatus'=>1)));
		if($refundMessage['count'] != 0)
		{
		    $return += $refundMessage['count'];
		}
		
		//订单流转
		$processMessage = R('orderProcess/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return += $processMessage['count'];
		}
		
		//优惠流转
		$processMessage = R('orderDiscount/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return += $processMessage['count'];
		}
		
		//亏损流转
		$processMessage = R('orderLoss/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return += $processMessage['count'];
		}
		
		//付款流转
		$processMessage = R('orderPayment/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return += $processMessage['count'];
		}
		
		//收款流转
		$processMessage = R('orderReceivables/count',array(array('dealStatus'=>1)));
		if($processMessage['count'] != 0)
		{
		    $return += $processMessage['count'];
		}
	}
	return $return;
}

//替换远程图片地址
function pic_remote($str)
{    
	$text=str_replace("\"","'",$str);
	$text=str_replace('src=\'','src=\''.C('website_url'),$text);
	return $text;
}

function isEmail($str) 
{
	if (empty($str) == true) {
		return false;
	}
	return preg_match('#[a-z0-9&\-_.]+@[\w\-_]+([\w\-.]+)?\.[\w\-]+#is', $str) ? true : false;
}

function isMobile($num) 
{
	if (empty($num) == true) {
		return false;
	}
	return preg_match('#^13[\d]{9}$|14^[0-9]\d{8}|^15[0-9]\d{8}$|^18[0-9]\d{8}$#', $num) ? true : false;
}

function areaSelect($id, $array, $default_str = '', $default_val = '' )
{
	//区域select
	$option = $default_str ? "<option value='$default_val'>$default_str</option>\r\n" : '';
	foreach ($array as $key => $value)
	{
		$selected = '';
		if ($value['id'] == $id)
		{
			$selected = ' selected="selected" ';
		}
		$option .= "<option value='{$value['id']}' $selected >{$value['name']}</option>\r\n";
	}
	return $option;
}

function productSelect($id, $array, $default_str = '', $default_val = '' )
{
	//产品select
	$option = $default_str ? "<option value='$default_val'>$default_str</option>\r\n" : '';
	foreach ($array as $key => $value)
	{
		$selected = '';
		if ($value['id'] == $id)
		{
			$selected = ' selected="selected" ';
		}
		$option .= "<option value='{$value['id']}' $selected >{$value['title']}</option>\r\n";
	}
	return $option;
}

function departureTimeSelect($id, $array, $default_str = '', $default_val = '' )
{
	//产品select
	$option = $default_str ? "<option value='$default_val'>$default_str</option>\r\n" : '';
	foreach ($array as $key => $value)
	{
		$selected = '';
		if ($value['id'] == $id)
		{
			$selected = ' selected="selected" ';
		}
		$option .= "<option value='{$value['id']}' $selected >".date("Y-m-d",$value['departuretime'])."</option>\r\n";
	}
	return $option;
}


function get_picture($str, $width = 0, $height = 0, $rnd = false) {

    //$ext = end(explode('.', $str));
    $ext = 'jpg';//原文件后缀
    $ext_dest = 'jpg';//生成缩略图格式
    $height = $height == 0? '' : $height;
    if (!empty($str)) {
        $str = preg_replace('/!(\d+)X(\d+)\.'.$ext_dest.'$/i', '', $str);//清除缩略图的!200X200.jpg后缀

        $ext = explode('.', $str);
        $ext = end($ext);
    }
    if (empty($ext) || !in_array(strtolower($ext), array('jpg','gif','png','jpeg'))) {
        $str = '';
    }
    if (empty($str)) {
        $str =  __ROOT__.'/uploads/system/nopic.png' ;
        $ext = 'png';
        $ext_dest = 'png';
        $width = 0;
    }
    if ($width == 0) {
        return $str;
    }

    $rndstr = $rnd ? '?random='.time() : '';
    return $str.'!'.$width. 'X' .$height. '.'. $ext_dest. $rndstr ;
}

/**
 * [uploadServerImg description]本地OA上传官网服务器
 * @param  [type] $file [description]
 * @param  [type] $sort [description]
 * @return [type]       [description]
 */
function uploadServerImg($file,$sort)
{
	switch ($sort) {
		case 'Travel_Reference':

			break;

		default:

			break;
	}

	$Ftp_Server   = '112.74.83.157';
	$Ftp_UserName = 'tripvip_it';
	$Ftp_User_Pwd = 'tripvip2015';

	$Conn_Id      = ftp_connect($ftp_server) or die("Couldn't connect to ".$ftp_server);
	$Login_Result = ftp_login($Conn_Id, $Ftp_UserName, $Ftp_User_Pwd);

	ftp_put($Conn_Id, $file, $file, FTP_BINARY);
	ftp_close($Conn_Id);
}

/**
 * @param integer去除法定假日
 * @param boolean
 */
function RemovalHoliday($day_nums = 5, $time = false)
{	
	if($time == false)$time = time();
	$return = array('day_nums'=>'0','time'=>$time);
	$d_array = array();

	for ($i=1; $i <= $day_nums; $i++)
	{
		$d_array[$i] = date('Ymd',$time +$i*24*60*60);
	}

	$return['time'] = strtotime(end($d_array));
	$d_str = implode(',', $d_array);
	$url   = 'http://www.easybots.cn/api/holiday.php?d='.$d_str;
	// 初始化一个 cURL 对象
	$curl = curl_init();

	// 设置你需要抓取的URL
	curl_setopt($curl, CURLOPT_URL, $url);

	// 设置header
	curl_setopt($curl, CURLOPT_HEADER, 0);

	// 设置cURL 参数，要求结果保存到字符串中还是输出到屏幕上。
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

	// 运行cURL，请求网页
	$data = curl_exec($curl);

	// 关闭URL请求
	curl_close($curl);

	// 显示获得的数据
	$data_arr = (Array)json_decode($data);
	$ii = '0';
	foreach ($data_arr as $key => $value)
	{
		if($value !== 0)$ii++;
	}

	$return['day_nums'] = $ii;

	return $return;
}

/**
 * @param  [type]清除所有空格
 * @return [type]
 */
function trimall($str)
{

    if(is_array($str))
    {
        return array_map('trimall', $str);
    }
    $qian=array(" ","　","\t","\n","\r");
    $hou=array("","","","","");
    return str_replace($qian,$hou,$str);
}

//groupID 0不发送组 格式1;2;3
//$userID 0不发送个人
function sendMessage($groupID,$userID,$title,$content,$type = 0,$sendID = false)
{
	if($sendID == false)
	{
		$sendID = 0;
	}
	
	if(empty($groupID) == false)
	{
		$groupIDArr = explode(";",$groupID);
		foreach ($groupIDArr as $key => $value)
		{
			$userIDArr = MOA('permission_user')->where(array('groupID'=>$value))->getField('id',true);
			foreach ($userIDArr as $key1 => $value1)
			{
				$data =array(
					'sendID'		=> 0,
					'type'			=> $type,
					'title'         => $title,
					'content'       => $content,
					'sendTime'		=> time(),
					'receiveID'		=> $value1,
					'receiveIDList'	=> $value1
				);
				M('message')->add($data);
			}
		}
		
	}
	
	if(empty($userID) == false)
	{
		$userIDArr = explode(";",$userID);
		foreach ($userIDArr as $key => $value)
		{
			$data =array(
					'sendID'		=> 0,
					'type'			=> $type,
					'title'         => $title,
					'content'       => $content,
					'sendTime'		=> time(),
					'receiveID'		=> $value,
					'receiveIDList'	=> $value
			);
			M('message')->add($data);
		}
	}
	
}

/**
 * [destination description]目的地
 * @param  [type] $destinationID [description]
 * @return [type]                [description]
 */
function destination($destinationID)
{
	$result1 = MOA('destination')->where(array('id'=>$destinationID))->getField('pid');
	$select1 = MOA('destination')->where(array('pid'=>$result1))->select();
	$select['html_three'] = '';
	$select['html_three'] .= '<select name="destination[]" onchange="select_address(this)" >';
	$select['html_three'] .= '<option value="0">请选择</option>';
	foreach ($select1 as $k1 => $v1) 
	{	
		if($v1['id'] == $destinationID)
		{	
			$select['html_three'] .= '<option value="'.$v1['id'].'" selected >'.$v1['name'].'</option>';
			if($v1['pid'] != '0000')
			{

				$result2 = MOA('destination')->field('id,pid')->where(array('id'=>$result1))->find();
				$select2 = MOA('destination')->where(array('pid'=>$result2['pid']))->select();
				$select['html_two'] = '';
		    	$select['html_two'] .= '<select name="destination[]" onchange="select_address(this)" >';
		    	$select['html_two'] .= '<option value="0">请选择</option>';
				foreach ($select2 as $k2 => $v2) 
				{	
					if($v2['id'] == $result1)
					{
						$select['html_two'] .= '<option value="'.$v2['id'].'" selected >'.$v2['name'].'</option>';
						if($v2['pid'] != '0000')
						{
							$result3 = MOA('destination')->field('id,pid')->where(array('id'=>$result2['pid']))->find();
							$select3 = MOA('destination')->where(array('pid'=>$result3['pid']))->select();
							$select['html_one'] = '';
					    	$select['html_one'] .= '<select name="destination[]" onchange="select_address(this)" >';
					    	$select['html_one'] .= '<option value="0">请选择</option>';
							foreach ($select3 as $k3 => $v3) 
							{	
								if($v3['id'] == $result2['pid'])
								{
									$select['html_one'] .= '<option value="'.$v3['id'].'" selected >'.$v3['name'].'</option>';
								}
								else
								{
									$select['html_one'] .= '<option value="'.$v3['id'].'" >'.$v3['name'].'</option>';
								}
							}
							$select['html_one'] .= '</select>';
						}
					}
					else
					{
						$select['html_two'] .= '<option value="'.$v2['id'].'" >'.$v2['name'].'</option>';
					}
				}
				$select['html_two'] .= '</select>';
			}
		}
		else
		{
			$select['html_three'] .= '<option value="'.$v1['id'].'" >'.$v1['name'].'</option>';
		}
	}
	$select['html_three'] .= '</select>';

	return $select;
}


/**
 * [randNums description]生成随机数
 * @param  integer $len    [description]
 * @param  string  $format [description]
 * @return [type]          [description]
 */
function randNums($length=6,$format='ALL')
{ 
    switch($format)
    {
        case 'ALL':
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            break;
        case 'CHAR':
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            break;
        case 'NUMBER':
            $chars='0123456789';
            break;
        default :
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            break;
    } 
    $strLen = strlen($chars);
    for($i=0;$i<$length;$i++)
    {
        $randStr .= $chars[mt_rand(0,$strLen-1)];    //生成php随机数

    }
    return $randStr;
}
function getEndDay( $start='now', $offset=0, $exception='', $allow='' ){
    //先计算不排除周六周日及节假日的结果
    $starttime = strtotime($start);
    $endtime = $starttime + $offset * 24 * 3600;
    $end = date('Y-m-d', $endtime);
    //然后计算周六周日引起的偏移
    $weekday = date('N', $starttime);//得到星期值：1-7
    $remain = $offset % 7;
    $newoffset = 2 * ($offset - $remain) / 7;//每一周需重新计算两天
    if( $remain > 0 ){//周余凑整
        $tmp = $weekday + $remain;
        if( $tmp >= 7 ){
            $newoffset += 2;
        }else if( $tmp == 6 ){
            $newoffset += 1;
        }
        //考虑当前为周六周日的情况
        if( $weekday == 6 ){
            $newoffset -= 1;
        }else if( $weekday == 7 ){
            $newoffset -= 2;
        }
    }
    //再计算节假日引起的偏移
    if( is_array($exception) ){//多个节假日
        foreach ($exception as $day){
            $tmp_time = strtotime($day);
            if( $tmp_time>$starttime && $tmp_time<=$endtime ){//在范围(a,b]内
                $weekday_t = date('N', $tmp_time);
                if($weekday_t <= 5){//防止节假日与周末重复
                    $newoffset += 1;
                }
            }
        }
    }else{//单个节假日
        if( $exception!='' ){
            $tmp_time = strtotime($exception);
            if( $tmp_time>$starttime && $tmp_time<=$endtime ){
                $weekday_t = date('N', $tmp_time);
                if($weekday_t <= 5){
                    $newoffset += 1;
                }
            }
        }

    }
    //根据偏移天数，递归做等价运算
    if($newoffset > 0){
        #echo "[{$start} -> {$offset}] = [{$end} -> {$newoffset}]"."<br />\n";
        return getEndDay($end,$newoffset,$exception,$allow);
    }else{
        return $end;
    }
}
/**
 * 暴力循环方法
 */
function getEndDay2( $start='now', $offset=0, $exception='', $allow='' ){
    $starttime = strtotime($start);
    $tmptime = $starttime + 24*3600;

    while( $offset > 0 ){
        $weekday = date('N', $tmptime);
        $tmpday = date('Y-m-d', $tmptime);
        $bfd = false;//是否节假日
        if(is_array($exception)){
            $bfd = in_array($tmpday,$exception);
        }else{
            $bfd = ($exception==$tmpday);
        }
        if( $weekday<=5 && !$bfd){//不是周末和节假日
            $offset--;
            #echo "tmpday={$tmpday}"."<br />";
        }
        $tmptime += 24*3600;
    }

    return $tmpday;
}

//得到预测日间
function getPredictionTime($orderid,$passportid)
{
        $passportFind=MOA('visa_passport')->where(array('orderid'=>$orderid,'passportid'=>$passportid))->find();
	    if(empty($passportFind)==false)
		{
		$passport_array=explode(',',$passportFind['passport_type']);
				$passport_list=array_unique($passport_array);
				$asignDays=0;
				foreach ($passport_list as $key => $value)
				{
					$passportTypeID= MOA('visa_passport_type')->where(array('id'=>$value))->getField('id');
					$passport_type = MOA('visa_day_set')->where(array('typeID'=>$passportTypeID))->find();
					
					if(empty($passport_type)==false)
					{
					   
					  $asignDays=$asignDays+$passport_type['set_day_nums'];
					
					}
					
				}
				return  $asignDays;
		}
}
//得到签证信息
function getVisaInformation($orderid,$passportid,$type)
{
    $passportFind=MOA('visa_passport')->where(array('orderid'=>$orderid,'passportid'=>$passportid))->find();
    if(empty($passportFind)==false)
    {

        $channel=MOA('visa')->where(array('id'=>$passportFind['oid']))->getField('channel');

        $passport_array=explode(',',$passportFind['passport_type']);
        $passport_list=array_unique($passport_array);
         
        foreach ($passport_list as $key => $value)
        {
            $visaPassportType= MOA('visa_passport_type')->where(array('id'=>$value))->find();
            if(empty($visaPassportType)==false)
            {
                $passportCountryID = MOA('visa_passport_type')->where(array('id'=>$visaPassportType['pid']))->getField('id');
                $passport_type = MOA('visa_day_set')->where(array('typeID'=>$visaPassportType['id']))->find();
                 
                if(empty($passportCountryID)==false&&empty($passport_type)==false)
                {
                    if($type==1)
                    {
                        $price[]        =$passport_type['cost'];
                        $passportType[] =$value;
                        $countryID[]    =$passportCountryID;
                        $channelID[]    =$channel;
                    }
                    else if($type==2)
                    {
                        $price[]        =$passport_type['onceDT'];
                        $passportType[] =$value;
                        $countryID[]    =$passportCountryID;
                        $channelID[]    =$channel;
                    }
                    else if($type==3)
                    {
                        $price[]        =$passport_type['moreDT'];
                        $passportType[] =$value;
                        $countryID[]    =$passportCountryID;
                        $channelID[]    = $channelID;
                    }
                    else if($type==4)
                    {
                        $price[]        =$passport_type['cost'];
                        $passportType[] =$value;
                        $countryID[]    =$passportCountryID;
                        $channelID[]    = $channelID;
                    }
                    else if($type==5)
                    {
                        $price[]        =$passport_type['extension'];
                        $passportType[] =$value;
                        $countryID[]    =$passportCountryID;
                        $channelID[]    = $channelID;
                    }
                    else if($type==6)
                    {
                        $price[]        =$passport_type['expeditedOneDay'];
                        $passportType[] =$value;
                        $countryID[]    =$passportCountryID;
                        $channelID[]    = $channelID;
                    }
                    else if($type==7)
                    {
                        $price[]        =$passport_type['expeditedTwoDay'];
                        $passportType[] =$value;
                        $countryID[]    =$passportCountryID;
                        $channelID[]    = $channelID;
                    }

                }
            }
        }
         
         
        return array($price,$passportType,$countryID,$channelID);
    }
}
//签证成本处理
function getVisaDeal($orderid,$passportid,$countryID,$type)
{
    $passportFind=MOA('visa_passport')->where(array('orderid'=>$orderid,'passportid'=>$passportid))->find();
    if(empty($passportFind)==false)
    {
        $channelID=MOA('visa')->where(array('id'=>$passportFind['oid']))->getField('channel');
    }

    $passportTypeArry=MOA('visa_passport_type')->where(array('pid'=>$countryID))->getField('id',true);

    $passportFind=MOA('visa_passport')->where(array('orderid'=>$orderid,'passportid'=>$passportid))->find();
    if(empty($passportFind)==false)
    {
        $passport_type=explode(',',$passportFind['passport_type']);
        $passportList=array_unique($passport_type);
        foreach ($passportList as $key => $value)
        {
            if (in_array($value, $passportTypeArry))
            {
                $findDaySet = MOA('visa_day_set')->where(array('typeID'=>$value))->find();
                if(empty($findDaySet)==false)
                {
                    if($type==1)
                    {
                        $price =$findDaySet['cost'];
                        $passportType=$value;
                    }
                    else if($type==2)
                    {
                        $price =$findDaySet['onceDT'];
                        $passportType=$value;
                    }
                    else if($type==3)
                    {
                        $price =$findDaySet['moreDT'];
                        $passportType=$value;
                    }
                    else if($type==4)
                    {
                        $price =$findDaySet['cost'];
                        $passportType=$value;
                    }
                    else if($type==5)
                    {
                        $price =$findDaySet['extension'];
                        $passportType=$value;
                    }
                    else if($type==6)
                    {
                        $price =$findDaySet['expeditedOneDay'];
                        $passportType=$value;
                    }
                    else if($type==7)
                    {
                        $price =$findDaySet['expeditedTwoDay'];
                        $passportType=$value;
                    }
                }
            }
        }
        return  array($price,$passportType,$channelID);
    }
}
//添加签证国家ID
function addCountryID($passportid)
{
    $findPassPortID= MOA('user_passport')->where(array('id'=>$passportid))->find();
    $passportFind=MOA('visa_passport')->where(array('orderid'=>$findPassPortID['orderid'],'passportid'=>$findPassPortID['passport_code']))->find();
    if(empty($passportFind)==false)
    {
        $passport_array=explode(',',$passportFind['passport_type']);
        $passport_list=array_unique($passport_array);
         
        foreach ($passport_list as $key => $value)
        {
            $passportTypeID= MOA('visa_passport_type')->where(array('id'=>$value))->find();
            $passport_country = MOA('visa_passport_type')->where(array('id'=>$passportTypeID['pid']))->getField('id');
            $findCountryID= MOA('user_passport_countryid')->where(array('passportID'=>$passportid))->find();
            if(empty($findCountryID)==true)
            {
                $data_countryID =array(
                    'passportID'           => $passportid,
                    'countryID'            => $passport_country,
                     
                );
                 
                MOA('user_passport_countryid')->add($data_countryID);
            }
        }
    }
}
//添加签证成本
function addCost($passportID,$price,$supplierID,$status,$passportType,$countryID,$channelID,$type)
{
    if($type==1)
    {
        $time=time();
    }
    else
    {
        $sendsignedTime=MOA('user_passport')->where(array('id'=>$passportID))->getField('sendsignedTime');
        if(empty($sendsignedTime)==false)
        {
            $time=$sendsignedTime;
        }
    }

     

    $data =array(
        'passportID'       => $passportID,
        'price'            => $price,
        'passportType'     => $passportType,
        'countryID'        => $countryID,
        'channelID'        => $channelID,
        'supplierID'       => $supplierID,
        'status'           => $status,
        'time'             => $time
    );
     
    $findDetails=MOA('visa_cost_details')->where(array('passportID'=>$passportID,'passportType'=>$passportType,'status'=>$status))->find();
    if(empty($findDetails)==true)
    {
        $id=MOA('visa_cost_details')->add($data);
    }

    if(empty($id)==false)
    {
         
        return  true;
    }
    else
    {
        return  false;
    }
     

}

function difficultSchedule($orderid,$passportid,$passport_code,$remarks)
{
    $data_schedule =array(
        'orderid'           => $orderid,
        'oid'                => $passportid,
        'passport_code'     => $passport_code,
        'remarks'           => $remarks,
        'adduser'            => getIdentyName(),
        'time'       	    => time(),
        'status'            => 10,
    );
    MOA('visa_schedule')->add($data_schedule);
    MOA('visa_schedule')->add($data_schedule);
    MOA('user_passport')->where(array('id'=>$passportid))->setField(array( 'status'=>2,'predictionAsignTime'=>'','asignTime'=>'','asign'=>0));
}

function difficultToNormal($passportid,$remarks,$type,$supplierID)
{

    if($type==1)
    {
        $return = array('valid'=>false,'msg'=>'');
        $passport=MOA('user_passport')->where(array('id'=>$passportid))->find();
        $visa_passport = MOA('visa_passport')->where(array('passportid'=>trim($passport['passport_code'])))->find();
        if(empty($visa_passport)==true)
        {
            $return['msg'] = '请在官网补充资料';
            return $return;
            exit;
        }
        else
        {
            MOA('visa_passport')->where(array('passportid'=>$visa_passport['passportid']))->setField(array('status'=>'1'));
            MOA('user_passport')->where(array('id'=>$passportid))->setField(array('orderid'=>$visa_passport['orderid']));

        }
    }



    $findPassport=MOA('user_passport')->where(array('id'=>$passportid))->find();
    if(empty($findPassport)==false)
    {

        foreach ($remarks as $key=>$value)
        {
            $data_schedule =array(
                'orderid'           => $findPassport['orderid'],
                'oid'               => $findPassport['id'],
                'passport_code'     => $findPassport['passport_code'],
                'remarks'           => $value,
                'adduser'           => getIdentyName(),
                'time'       	    => time(),
                'status'            => 2,
            );
            MOA('visa_schedule')->add($data_schedule);
            MOA('visa_schedule')->add($data_schedule);
            	
        }
        	
        	
        $asignDays=getPredictionTime($findPassport['orderid'],$findPassport['passport_code']);
        
        //获得成本
        $visaArray=getVisaInformation($findPassport['orderid'],$findPassport['passport_code'],1);
        foreach ($visaArray[0] as $key=>$value)
        {
         addCost($passportid,$value,$supplierID,1,$visaArray[1][$key],$visaArray[2][$key],$visaArray[3][$key],$type);
        }
        	
        $exception = array(
            '2016-01-01','2016-02-08','2016-02-09','2016-02-10','2016-02-11','2016-02-12','2016-04-04','2016-04-13','2016-04-14','2016-04-15','2016-05-02','2016-06-09','2016-06-10','2016-08-12','2016-09-15','2016-09-16','2016-10-03','2016-10-04','2016-10-05','2016-10-06'
        );
        	
        	
        if(empty($findPassport['sendsignedTime'])==false)
        {
            $time=$findPassport['sendsignedTime'];
        }
        else
        {
            $time=time();
        }
        	
        $predictionTime=getEndDay(date('Y-m-d',$time),$asignDays,$exception);
        	
        $data_schedule3 =array(
            'orderid'           => $findPassport['orderid'],
            'oid'               => $findPassport['id'],
            'passport_code'     => $findPassport['passport_code'],
            'remarks'           => '预估'.$predictionTime.'可以出签,实际出签时间以领馆安排为准',
            'adduser'           => getIdentyName(),
            'time'       	    => time(),
            'status'            => 8,
        );
        MOA('visa_schedule')->add($data_schedule3);
        MOA('visa_schedule')->add($data_schedule3);
        	

        	
        $data=array(
            'sendsignedTime'=>$time,
            'status'=>1,
            'pass'=>1,
            'sendsigned'=>1,
            'check'=>1,
            'predictionAsignTime'=>strtotime($predictionTime),
            'supplierID'=>$supplierID
            //'cost' =>$cost
            	
        );
        MOA('user_passport')->where(array('id'=>$passportid))->save($data);
        MOA('visa_schedule')->where(array('oid'=>$passportid))->setField(array('orderid'=>$findPassport['orderid']));
        MOA('visa_schedule')->where(array('oid'=>$passportid))->setField(array('orderid'=>$findPassport['orderid']));
        	
        addCountryID($passportid);
   	
        $findID=MOA('user_passport')->where(array('id'=>$passportid))->find();
        $findDepartureTime = MOA('visa')->where(array('orderid'=>$findPassport['orderid']))->getField('departuretime');
        if($findID['predictionAsignTime'] > $findDepartureTime)
        {
            MOA('user_passport')->where(array('id'=>$passportid))->setField(array('lessAsign'=>1));
        }
        	
        if($type==1)
        {
            $return['valid'] = true;
            return $return;
        }


    }
}

function normalToDifficult($passportid,$remarks)
{
    MOA('user_passport')->where(array('id'=>$passportid))->setField(array('asign'=>0,'asignTime'=>'','sendsigned'=>0,'sendsignedTime'=>'', 'status'=>2,'pass'=>0,'predictionAsignTime'=>''));
    $passportFind=MOA('user_passport')->where(array('id'=>$passportid,'status'=>2))->find();
    $data_schedule =array(
        'orderid'           => $passportFind['orderid'],
        'oid'               => $passportFind['id'],
        'passport_code'     => $passportFind['passport_code'],
        'remarks'           => $remarks,
        'adduser'           => getIdentyName(),
        'time'       	    => time(),
        'status'            => 10,
        	
    );
    MOA('visa_schedule')->add($data_schedule);
    MOA('visa_schedule')->add($data_schedule);
}


function modifySendSignedTime($passportid,$remarks,$sendTime,$type)
{
    $findPassport=MOA('user_passport')->where(array('id'=>$passportid))->find();
    if(empty($findPassport)==false)
    {
        foreach ($remarks as $key=>$value)
        {
            $data_schedule =array(
                'orderid'           => $findPassport['orderid'],
                'oid'               => $findPassport['id'],
                'passport_code'     => $findPassport['passport_code'],
                'remarks'           => $value,
                'adduser'           => getIdentyName(),
                'time'       	    => time(),
                'status'            => 2,
            );
            MOA('visa_schedule')->add($data_schedule);
            MOA('visa_schedule')->add($data_schedule);
        }
        	
        $asignDays=getPredictionTime($findPassport['orderid'],$findPassport['passport_code']);
        	
        $exception = array(
            '2016-01-01','2016-02-08','2016-02-09','2016-02-10','2016-02-11','2016-02-12','2016-04-04','2016-04-13','2016-04-14','2016-04-15','2016-05-02','2016-06-09','2016-06-10','2016-08-12','2016-09-15','2016-09-16','2016-10-03','2016-10-04','2016-10-05','2016-10-06'
        );
        	
        $predictionTime=getEndDay($sendTime,$asignDays,$exception);
        	
        $data_schedule2 =array(
            'orderid'           => $findPassport['orderid'],
            'oid'               => $findPassport['id'],
            'passport_code'     => $findPassport['passport_code'],
            'remarks'           => '预估'.$predictionTime.'出签,实际出签时间以领馆安排为准',
            'adduser'           => getIdentyName(),
            'time'       	    => time(),
            'status'            => 12,
        );
        MOA('visa_schedule')->add($data_schedule2);
        MOA('visa_schedule')->add($data_schedule2);
        	
        if($type=='dt')
        {
            MOA('user_passport')->where(array('id'=>$passportid))->setField(array('asign'=>0,'asignTime'=>'','sendsigned'=>0,'sendsignedTime'=>strtotime($sendTime),'predictionAsignTime'=>strtotime($predictionTime)));
        }
        	
    }
}

function getVisaProcessNextGroup($passportID)
{
	$visaMessage = MOA('message_visa')->where(array('passportID'=>$passportID,'status'=>0))->find();
	
	if(empty($visaMessage) == false)
	{
		return MOA('permission_group')->where(array('id'=>$visaMessage['receiveGroupID']))->getField('title');
	}
}

function Messagesurplu_sum()
{
	$url                = 'http://211.147.252.14:8080/Balance.asp?';
	$params             = array();
	$params['CORPID']   = 'lv001-0060';
	$params['USERNAME'] = 'tripvipcn';
	$params['PASSWORD'] = '111111';

	foreach ($params as $key => $value)
	{
		$url.= $key."=".$value."&";
	}

	$url    = trim($url,'&');
	$return = curlRequest($url);
	
	return $return;
}


function curlRequestWeiXin($url,$data=array()){
    //对空格进行转义
    $url = str_replace(' ','+',$url);
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, "$url");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch,CURLOPT_TIMEOUT,3);  //定义超时3秒钟  
     // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));    
    
    //执行并获取url地址的内容
    $output = curl_exec($ch);
    $errorCode = curl_errno($ch);
    //释放curl句柄
    curl_close($ch);
    if(0 !== $errorCode) {
        return false;
    }
    return $output;

}

function weChatMessage($type,$mobile,$first,$keyword1,$keyword2,$keyword3,$remark)
{
	$url = 'http://www.tripvip.cn/Public/getWeChatMessage?';
	$params = array();
	$params['type']     = $type;
	$params['mobile']   = $mobile;
	$params['first']    = $first;
	$params['keyword1'] = $keyword1;
	$params['keyword2'] = $keyword2;
	$params['keyword3'] = $keyword3;
	$params['remark']   = $remark;
	
	foreach ($params as $key => $value)
	{
		$url.= $key."=".$value."&";
	}
	$url = trim($url,'&');
	$return = curlRequest($url);
	return $return;
	
  
}

/**
 * 发送微信企业号消息
 * $msgType  消息类型 1表示只读，不带链接地址  2表示带链接地址
 * $agentID 企业应用的id，整型。 5表示OA系统消息  6表示OA站内信息 7表示 OA订单流转 8表示OA签证流转 9表示OA成本付款流转 10表示 OA退款流转
 * $content 消息内容
 * $userID 成员ID列表，一维数组传递['1', '2', ...]，最多1000个，默认发送给全部成员
 * $departmentID 部门ID列表，一维数组传递['1', '2', ...]，最多1000个
 */
function WeChatBizMessage($msgType,$agentID,$content= array(),$userID = array(),$departmentID = array())
{
    $data['msgType'] 	    =$msgType;
    $data['agentID'] 	    =$agentID;
    $data['content']        =$content;
    $data['userID'] 	    =$userID;
    $data['departmentID'] 	=$departmentID;
    $return = curlRequest_array('http://www.tripvip.cn/Weixin/bizApp',$data);
    return $return;
} 

function message($id = false,$parameters = array(),$mobile= false,$email= false,$mode,$type)
{
		if(empty($id) == false)
		{
			$data['id'] 	=$id;
		}
	
	     $data['parameters'] =$parameters;
		
		if(empty($mobile) == false)
		{
			$data['mobile'] 	=$mobile;
		}
		if(empty($email) == false)
		{
			$data['email'] 	=$email;
		}
		if(empty($type) == false)
		{
		    $data['type'] ='order';
		}
		else
		{
		    $data['type'] =$type;
		}
		$data['mode'] 	=$mode;
		
		

		$return = curlRequest_array('http://www.tripvip.cn/Public/getMessage',$data);
		$result['valid'] = true;
		$return['msg'] = '发送成功';
		return $return;
   
}

function curlRequest_array($url,$data=array()){
    //对空格进行转义
    $url = str_replace(' ','+',$url);
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, "$url");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch,CURLOPT_TIMEOUT,3);  //定义超时3秒钟  
     // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));    
    
    //执行并获取url地址的内容
    $output = curl_exec($ch);
    $errorCode = curl_errno($ch);
    //释放curl句柄
    curl_close($ch);
    if(0 !== $errorCode) {
        return false;
    }
    return $output;

}

function QRCode($uid)
{

	$url = "http://m.tripvip.cn/mobile/Halfshop/fun150925s02?uid=".$uid;//要生成二维码的网址
	return urlencode($url);
}


/**
 * [departureHtml description]
 * @param  [type]  $departureCityIDStr [description]
 * @param  boolean $name               [description]
 * @return [type]                      [description]
 */
function departureHtml($departureCityIDStr,$name = false)
{
	$departureCityIDArr     = explode('|', $departureCityIDStr);
	$departureCityIDArrNums = count($departureCityIDArr);
	$departureCityArr       = MOA('departure')->field('id,name')->order('sort')->select();
	$departureHtml          = array();
	$name = isset($name) ? $name : 'departureCityID[]';

	for ($i=0; $i < $departureCityIDArrNums; $i++)
	{
		$departureHtml[$i] = '';
		$departureHtml[$i] .= '<select name="'.$name.'">';
		$departureHtml[$i] .= '<option value="0">请选择城市</option>';
		foreach ($departureCityArr as $key => $value)
		{
			if($departureCityIDArr[$i] == $value['id'])
			{
				$departureHtml[$i] .= '<option value="'.$value['id'].'" selected >'.$value['name'].'</option>';
			}
			else
			{
				$departureHtml[$i] .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
			}
		}
		$departureHtml[$i] .= '</select>';
	}

	return $departureHtml;
}
/**
 * [destinationHtml description]
 * @return [type] [description]
 */
function destinationHtml($destinationID, $name = false, $deep = '1', $function = false)
{
	$destinationPID = MOA('destination')->where(array('id'=>$destinationID))->getField('pid');
	$destinationPID = isset($destinationPID) ? $destinationPID : '0';
	$destinationArr = MOA('destination')->where(array('pid'=>$destinationPID))->order('sort')->select();
	switch ($deep)
	{
		case '1':
			$htmlName = '大洲';
			$name = isset($name) ? $name : 'areaID[]';
			break;
		case '2':
			$htmlName = '国家';
			$name = isset($name) ? $name : 'countryID[]';
			break;
		case '3':
			$htmlName = '城市';
			$name = isset($name) ? $name : 'cityID[]';
			break;
		default:
			$htmlName = '大洲';
			$name = isset($name) ? $name : 'areaID[]';
			break;

	}

	$destinationHtml = '';
	$destinationHtml .= '<select name="'.$name.'" onChange="'.$function.'" >';
	$destinationHtml .= '<option value="0">请选择'.$htmlName.'</option>';
	foreach ($destinationArr as $key => $value)
	{
		if($destinationID == $value['id'])
		{
			$destinationHtml .= '<option value="'.$value['id'].'" selected >'.$value['name'].'</option>';
		}
		else
		{
			$destinationHtml .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
		}
	}
	$destinationHtml .= '</select>';

	return $destinationHtml;
}

/**
 * [destinationChildHtml description]
 * @return [type] [description]
 */
function destinationChildHtml($destinationID)
{
	$destinationArr = MOA('destination')->where(array('pid'=>$destinationID))->select();

	$destinationHtmlOption = '';
	foreach ($destinationArr as $key => $value)
	{
		$destinationHtmlOption .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
	}

	return $destinationHtmlOption;
}
/**
 * [provinceHtml description]
 * @return [type] [description]
 */
function provinceHtml()
{
	$provinceArr = MOA('address_province')->order('province_id')->select();
	$provinceHtml = '';
	$provinceHtml .= '<select name="provinceID" >';
	$provinceHtml .= '<option value="0">请选择省份</option>';
	foreach ($provinceArr as $key => $value)
	{
		$provinceHtml .= '<option value="'.$value['province_id'].'">'.trim($value['province_name']).'</option>';
	}
	$provinceHtml .= '</select>';

	return $provinceHtml;
}

/*
* 判断考勤状态
*/
function judgeTime($onTime, $offTime, $scheduling, $punchID=''){
	$workingtime = MOA('timesheet_workingtime')->getField('WorkId,WorkOn,WorkOff', true);
	$punchInfo = MOA('timesheet_punch')->where("PunchId=$punchID")->find();
	$WorkHours = $offTime - $onTime;
	$buff = 60 * 60;  //缓冲时间
	$workHour = ($WorkHours - 3600 + $buff) / 3600;
	switch ($scheduling) {
		case '1':
			$NormalWorkHours = 8;
			if ($workHour >= 8) {
				$Leaveearly = false;
			} else if ($workHour < 8 && $workHour > 0) {
				$Leaveearly = true;
			}
			break;
		case '2':
			$NormalWorkHours = 6.5;
			if ($workHour >= 6.5) {
				$Leaveearly = false;
			} else if ($workHour < 6.5 && $workHour > 0) {
				$Leaveearly = true;
			}
			break;
		case '3':
			$NormalWorkHours = 8;
			if ($workHour >= 8) {
				$Leaveearly = false;
			} else if ($workHour < 8 && $workHour > 0) {
				$Leaveearly = true;
			}
			break;
		case '4':
			$NormalWorkHours = 6.5;
			if ($workHour >= 6.5) {
				$Leaveearly = false;
			} else if ($workHour < 6.5 && $workHour > 0) {
				$Leaveearly = true;
			}
			break;
	}

	$WorkOn = (strtotime(date('H:i', $workingtime[$scheduling]['WorkOn'])) + $buff - strtotime(date('H:i', $onTime))) / 60;
	//$WorkOff= (strtotime(date('H:i',$workingtime[$scheduling]['WorkOff']))+600-strtotime(date('H:i',$kq3['ActWorkOff'])))/60;
	//迟到
	if ($WorkOn < 0) {
		$WorkState2 = 1;
	} else {
		$WorkState2 = 0;
	}
	//早退
	if ($Leaveearly == true) {
		$WorkState3 = 1;
	} else {
		$WorkState3 = 0;
	}
	//正常
	if ($WorkOn >= 0 && $Leaveearly == false) {
		$WorkState1 = 1;
		//$WorkHours = $NormalWorkHours;
	} else {
		$WorkState1 = 0;
		//$WorkHours = round($workHour, 1) > 8 ? 8 : round($workHour, 1);
	}
	if(!empty($onTime) && !empty($offTime)) {
		$WorkHours = $NormalWorkHours;
	}

	//判断是否有请假调休记录，有则不算早退或迟到
	if(!empty($punchID)) {
		$punchInfo = MOA('timesheet_punch')->where("PunchId=$punchID")->find();
		if (!empty($punchInfo['LeaveTime'])) {
			$WorkState2 = 0;
			$WorkState3 = 0;
		}
	}

	$return = array('WorkState1'=>$WorkState1,'WorkState2'=>$WorkState2,'WorkState3'=>$WorkState3,'WorkType'=>$scheduling,'WorkHours'=>$WorkHours);

	return $return;
}

//更新 考勤天数 记录
function updateStatistics($params){
	$userID = $params['userID'];
	$punchMonth = $params['punchMonth'];
	$punchMonth = mktime(0,0,0,date('m',$punchMonth),1,date('Y',$punchMonth));

	if(empty($userID)){
		$userIDs = MOA('timesheet_punch')->group('UserId')->getField('UserId', true);
	}else{
		$userIDs = array($userID);
	}

	foreach($userIDs as $key=>$userID) {
		$HoursList = MOA('timesheet_punch')->where(array('UserId' => $userID, 'PunchMonth' => $punchMonth))->select();
		$OverHours = 0;
		$LeaveDays = 0;
		$LateDays = 0;
		foreach ($HoursList as $key => $value) {
			$OverHours = $OverHours + $value['OverHours'];
			$LeaveDays = $LeaveDays + $value['LeaveTime'];
			$LateDays = $LateDays + $value['WorkState2'];
		}

		$count = array();
		$count['workDays'] = MOA('timesheet_scheduling')->where(array('UserId' => $userID, 'SchedulingMonth' => $punchMonth))->count();
		$realityWorkDays = MOA('timesheet_punch')->where(array('UserId' => $userID, 'PunchMonth' => $punchMonth))->count();
		$count['realityWorkDays'] = $realityWorkDays + $OverHours / 8 - $LeaveDays / 8;
		$count['leaveDays'] = $LeaveDays / 8;
		$count['lateDays'] = $LateDays;

		$dataStatistics = array(
			'workDays' => $count['workDays'],
			'realityWorkDays' => $count['realityWorkDays'],
			'leaveDays' => $count['leaveDays'],
			'lateDays' => $count['lateDays'],
			'year' => date('Y', $punchMonth),
			'month' => date('m', $punchMonth)
		);
		$findStatistics = MOA('timesheet_statistics')->where(array('userID' => $userID, 'statisticsMonth' => $punchMonth))->find();
		if (empty($findStatistics) == false) {
			$res = MOA('timesheet_statistics')->where(array('userID' => $userID, 'statisticsMonth' => $punchMonth))->save($dataStatistics);
		} else {
			$dataStatistics['userID'] = $userID;
			$dataStatistics['statisticsMonth'] = $punchMonth;
			$res = MOA('timesheet_statistics')->add($dataStatistics);
		}
	}

	return $dataStatistics;
}
?>